package com.example.nettydemo.网络编程.TCP;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

public class 客户端 implements Runnable {
    @Override
    public void run(){

    }
    public static void main(String[] args) {
        Socket socket = null;
        OutputStream os = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        try {
            //创建Socket对象，指明服务器端的ip和端口号
//            InetAddress inet = InetAddress.getByName("127.0.0.1");
            InetAddress inet = InetAddress.getLocalHost();
            socket = new Socket(inet,65534);
            os = socket.getOutputStream();//获取输出流  获得输出数据
            os.write("你好，我是客户端\n".getBytes());//写出数据操作
            os.flush();
            socket.shutdownOutput();//关闭输出流

            baos = new ByteArrayOutputStream();
            is = socket.getInputStream();
            byte[] bytes = new byte[5];
            int len;
            while ((len = is.read(bytes)) != -1) {
                baos.write(bytes, 0, len);//把输入流的内容  写道ByteArrayOutputStream里
            }
            System.out.println(socket.getInetAddress() + ":" + baos.toString());


        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                baos.close();
                is.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}
